<template>
  <div class="index">
    <header>
      <div @click="gocities">
        {{ state.city }}
        <img src="@/assets/img/index/daosanjiao.png" class="dsj" />
      </div>
      <van-search
        v-model="value"
        placeholder="一号线/二号线"
        shape="round"
        background="transparent"
        @search="onSearch"
        @clear="onClear"
      >
        <template #left-icon>
          <img class="fang" src="@/assets/img/index/fang.png" />
        </template>
      </van-search>
    </header>
    <van-pull-refresh v-model="state.loading2" @refresh="onRefresh">
      <div class="classify">
        <van-grid :column-num="5" :border="false">
          <van-grid-item text="单间">
            <template #icon>
              <img src="@/assets/img/index/dan.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="整套">
            <template #icon>
              <img src="@/assets/img/index/zheng.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="品牌公寓" to="/brand">
            <template #icon>
              <img src="@/assets/img/index/pinpai.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="月租房源">
            <template #icon>
              <img src="@/assets/img/index/yue.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="新上架">
            <template #icon>
              <img src="@/assets/img/index/new.png" />
            </template>
          </van-grid-item>
        </van-grid>
        <van-grid :column-num="5" :border="false" class="second">
          <van-grid-item text="地图找房">
            <template #icon>
              <img src="@/assets/img/index/ditu.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="通勤找房" to="/commute">
            <template #icon>
              <img src="@/assets/img/index/ditie.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="帮我找房" to="/help">
            <template #icon>
              <img src="@/assets/img/index/ss.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="找室友" to="/roommate">
            <template #icon>
              <img src="@/assets/img/index/shiyou.png" />
            </template>
          </van-grid-item>
          <van-grid-item text="发布房源">
            <template #icon>
              <img src="@/assets/img/index/fangyuan.png" />
            </template>
          </van-grid-item>
        </van-grid>
      </div>
      <div class="banner">
        <div class="left">
          <img src="@/assets/img/index/img1.png" />
        </div>
        <div class="right">
          <div class="top">
            <img src="@/assets/img/index/img2.png" />
          </div>
          <div class="bot">
            <img src="@/assets/img/index/img3.png" />
            <img src="@/assets/img/index/img4.png" class="four" />
          </div>
        </div>
      </div>
      <div class="ad">
        <div class="top">
          <img src="@/assets/img/index/baletu.png" class="baletuimg" />
          <span>专属服务</span>
        </div>
        <p>海量真房源·租金可月付·租期有保障</p>

        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item
            ><img src="@/assets/img/index/banner1.png"
          /></van-swipe-item>
          <van-swipe-item
            ><img src="@/assets/img/index/banner2.png"
          /></van-swipe-item>
          <van-swipe-item
            ><img src="@/assets/img/index/banner3.png"
          /></van-swipe-item>
          <van-swipe-item
            ><img src="@/assets/img/index/banner4.png"
          /></van-swipe-item>
        </van-swipe>
      </div>
      <div class="recommend">
        <div class="up">
          <div class="top">
            <img src="@/assets/img/index/baletu.png" class="baletuimg" />
            <span>推荐房源</span>
          </div>
          <van-dropdown-menu :direction="direction">
            <van-dropdown-item
              v-model="state.value1"
              :options="option1"
              @change="changehouse(state.value1)"
            />
            <van-dropdown-item
              v-model="state.value2"
              :options="option2"
              @change="changehouse2(state.value2)"
            />
            <van-dropdown-item v-model="state.value3" :options="option3" />
            <van-dropdown-item v-model="state.value4" :options="option4" />
            <van-dropdown-item
              v-model="state.value5"
              :options="option5"
              @change="changehouse5(state.value5)"
            />
          </van-dropdown-menu>
        </div>

        <!-- 上拉加载 -->
        <div class="father">
          <van-list
            v-model:loading="state.loading"
            :finished="state.finished"
            finished-text="没有更多了"
            @load="onLoad"
            :immediate-check="true"
            offset="0"
          >
            <lazy-component class="van-clearfix">
              <van-cell
                v-for="(item, i) in state.list"
                :key="item._id"
                :style="{ marginTop: i % 2 != 0 && i != 1 ? '30px' : '12px' }"
                class="van-clearfix"
              >
                <template #value>
                  <img
                    :src="item.imgUrl"
                    class="houseimg"
                    @click="todetail(item.house_id)"
                  />
                  <div class="bot">
                    <div>
                      <span>{{ item.lease }}</span> {{ item.apartment }}
                    </div>
                    <div class="sp">
                      <span
                        class="let"
                        v-for="(val, index) in item.inform"
                        :key="val"
                        >{{ val }}<i v-if="index + 1 < item.inform.length">·</i>
                      </span>
                    </div>
                    <div class="price">{{ item.price }} 元/月</div>
                    <img
                      :src="likeimgsrc(item.house_id)"
                      class="like"
                      :ac="item.house_id"
                      @click="likehouse($event, item.house_id)"
                    />
                  </div>
                  <p class="info">
                    <van-icon name="aim" color="#fff" />&nbsp;
                    {{ item.route }}&nbsp;
                    {{ item.region }}
                  </p>
                </template>
              </van-cell>
            </lazy-component>
          </van-list>
        </div>
      </div>
      <div class="back" v-if="state.back" @click="goback">
        <van-icon name="back-top" />
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onDeactivated, computed } from "vue";
import {
  getRenderData,
  getIndexData,
  choiceRoute,
  choiceRegion,
  chioceData,
  priceAscOrder,
  priceDescOrder,
  collectHouseData,
} from "../../utils/app.js";
import { Toast } from "vant";
import { useRouter, useRoute } from "vue-router";
export default {
  setup() {
    const router = useRouter();
    const route = useRoute();
    const value = ref("");
    const data = reactive({
      housesData: {},
    });
    let direction = ref("up");

    const state = reactive({
      value1: 0,
      value2: 0,
      value3: "a",
      value4: "a",
      value5: 0,
      list: [],
      loading: false,
      finished: false,
      post: { pageSize: 6, currentPage: 1 },
      count: 0,
      loading2: false,
      back: false,
      likeimg: require("../../assets/img/index/like.png"),
      city: "杭州",
    });
    const option1 = [
      { text: "地铁", value: 0 },
      { text: "一号线", value: 1 },
      { text: "二号线", value: 2 },
      { text: "三号线", value: 3 },
      { text: "四号线", value: 4 },
      { text: "五号线", value: 5 },
    ];
    const option2 = [
      { text: "区域", value: 0 },
      { text: "上城区", value: 1 },
      { text: "江干区", value: 2 },
      { text: "萧山区", value: 3 },
      { text: "余杭区", value: 4 },
      { text: "拱墅区", value: 5 },
    ];
    const option3 = [
      { text: "租金", value: "a" },
      { text: "1000 以下", value: "b" },
      { text: "1000-2000", value: "c" },
      { text: "2000-3000", value: "d" },
      { text: "3000-4000", value: "e" },
      { text: "4000 以上", value: "f" },
    ];
    const option4 = [
      { text: "筛选", value: "a" },
      { text: "租金月付", value: "b" },
      { text: "近地铁", value: "c" },
      { text: "非一楼", value: "d" },
      { text: "朝南", value: "e" },
    ];
    const option5 = [
      { text: "排序", value: 0 },
      { text: "按价格升序", value: 1 },
      { text: "按价格降序", value: 2 },
    ];

    //跳转城市页面
    const gocities = () => {
      router.push({ path: "/cities", query: { city: state.city } });
    };

    //选取信息
    const changehouse = async (val) => {
      if (val == 0) {
        state.list = [];
        state.post.currentPage = 1;
        state.finished = false;
      } else {
        state.post.currentPage = 1;
        state.finished = true;
        if (state.value2 == 0) {
          const a = await choiceRoute({
            route: option1[val].text,
          });
          state.list = a.list;
        } else {
          const a = await chioceData({
            route: option1[val].text,
            region: option2[state.value2].text,
          });
          state.list = a.list;
        }
      }
    };

    const changehouse2 = async (val) => {
      if (val == 0) {
        state.list = [];
        state.post.currentPage = 1;
        state.finished = false;
      } else {
        state.post.currentPage = 1;
        state.finished = true;
        if (state.value1 == 0) {
          const a = await choiceRegion({
            region: option2[val].text,
          });
          state.list = a.list;
        } else {
          const a = await chioceData({
            route: option1[state.value1].text,
            region: option2[val].text,
          });
          state.list = a.list;
        }
      }
    };

    const changehouse5 = async (val) => {
      if (val == 0) {
        state.list = [];
        state.post.currentPage = 1;
        state.finished = false;
      } else if (val == 1) {
        state.value1 = state.value2 = 0;
        state.post.currentPage = 1;
        state.finished = true;
        const a = await priceAscOrder();
        state.list = a.list;
      } else if (val == 2) {
        state.post.currentPage = 1;
        state.finished = true;
        const a = await priceDescOrder();
        state.list = a.list;
      }
    };
    //搜索
    const onSearch = async (val) => {
      const a = await choiceRoute({ route: val });
      state.post.currentPage = 1;
      state.finished = true;
      state.list = a.list;
    };

    //清空搜索
    const onClear = () => {
      state.list = [];
      state.finished = false;
    };

    const onLoad = async () => {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      data.housesData = await getIndexData(state.post);
      state.post.currentPage += 1;
      state.list.push(...data.housesData.list);
      state.loading = false;
      if (state.list.length >= data.housesData.count) {
        state.finished = true;
      }
    };

    //下拉刷新
    const onRefresh = () => {
      setTimeout(() => {
        Toast("刷新成功");
        state.loading2 = false;
        state.count++;
        data.housesData = [];
        state.list = [];
        state.post.currentPage = 1;
        state.finished = false;
        state.value1 = 0;
        state.value2 = 0;
        value.value = "";
        state.back = false;
        state.value5 = 0;
      }, 500);
    };

    const getAllData = async () => {
      data.housesData = await getRenderData();
    };

    const getDate = async () => {
      data.housesData = await getIndexData(state.post);
      state.post.currentPage += 1;
      state.list.push(...data.housesData.list);
    };

    //跳转详情页
    const todetail = (id) => {
      router.push("/detail/" + id);
    };

    //加入收藏
    const likehouse = (el, id) => {
      if (
        !localStorage.getItem("token") ||
        localStorage.getItem("token") == ""
      ) {
        router.push("/login");
      } else {
        const gathers = JSON.parse(localStorage.getItem("gather"));
        if (gathers.includes(id)) {
          gathers.splice(gathers.indexOf(id), 1);
          el.target.src = require("@/assets/img/index/like.png");
        } else {
          gathers.push(id);
          el.target.src = require("@/assets/img/index/like2.png");
        }
        localStorage.setItem("gather", JSON.stringify(gathers));
        collectHouseData({
          token: localStorage.getItem("token"),
          gather: gathers,
        });
        // state.likeimg = require("@/assets/img/index/like2.png");
        // el.target.src = require("@/assets/img/index/like2.png");
      }
    };

    const likeimgsrc = computed(() => (el) => {
      if (
        localStorage.getItem("token") &&
        localStorage.getItem("token") != ""
      ) {
        const gathers = JSON.parse(localStorage.getItem("gather"));
        if (gathers.includes(el)) {
          return require("@/assets/img/index/like2.png");
        } else {
          return state.likeimg;
        }
      } else {
        return state.likeimg;
      }
    });

    onMounted(() => {
      // const gathers = JSON.parse(localStorage.getItem("gather"));
      // console.log(route.query.city);
      if (route.query.city && route.query.city != "") {
        state.city = route.query.city;
      }
      window.addEventListener("scroll", getScroll);
    });

    onDeactivated(() => {
      window.removeEventListener("scroll", getScroll);
    });

    const getScroll = () => {
      const top = document.documentElement.scrollTop;
      if (top > 300) {
        state.back = true;
      } else {
        state.back = false;
      }
      if (top > 370) {
        direction.value = "down";
      } else {
        direction.value = "up";
      }
    };

    const goback = () => {
      document.documentElement.scrollTop = 0;
      state.back = false;
    };

    return {
      value,
      state,
      option1,
      option2,
      direction,
      option3,
      option4,
      option5,
      data,
      likeimgsrc,
      getAllData,
      getDate,
      onRefresh,
      onLoad,
      todetail,
      likehouse,
      changehouse,
      changehouse2,
      changehouse5,
      onSearch,
      onClear,
      getScroll,
      goback,
      gocities,
    };
  },
};
</script>

<style lang="less">
.index {
  overflow: visible;
  background: #fbfbfb;
  position: relative;
  header {
    width: 100%;
    z-index: 6;
    position: fixed;
    top: 0;
    background: #fff;
    padding: 15px;
    font-size: 16px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .dsj {
      width: 11px;
      vertical-align: middle;
    }
    .fang {
      width: 18px;
      vertical-align: middle;
      margin-left: 5px;
    }
    .van-search {
      width: 275px;
      height: 30px;
      padding: 0;
      .van-cell {
        background-color: #f2f2f2;
        border-radius: 25px;
      }
      .van-field__control {
        font-size: 14px;
      }
    }
  }
  .classify {
    margin-top: 60px;
    background: #fff;
    padding-left: 8px;
    padding-right: 8px;
    .van-grid-item__text {
      font-size: 12px;
    }
    .van-badge__wrapper img {
      width: 50px;
    }
    .second {
      .van-grid-item__content {
        padding-top: 0;
      }
      .van-badge__wrapper img {
        width: 18px;
      }
    }
  }
  .banner {
    background: #fff;
    overflow: hidden;
    padding: 0 15px;
    .left {
      float: left;
      img {
        width: 172px;
      }
    }
    .right {
      margin-left: 4px;
      float: left;
      .top {
        height: 86px;
        img {
          width: 169px;
        }
      }
      .four {
        margin-left: 3px;
      }
      .bot img {
        width: 83px;
      }
    }
  }
  .ad {
    background: #fff;
    padding: 20px 10px 0;
    .top {
      img {
        width: 80px;
        // vertical-align: bottom;
      }
      span {
        font-size: 18px;
        vertical-align: middle;
        margin-left: 5px;
        color: #666;
      }
    }
    p {
      font-size: 14px;
      margin-left: 6px;
      color: #bbb;
      margin-top: 10px;
    }
    .van-swipe-item {
      margin-top: 20px;
      img {
        width: 351px;
      }
    }
  }
  .recommend {
    overflow: hidden;
    .up {
      padding: 20px 10px 0;
      background: #fff;
      // margin-bottom: 1px;
    }
    .top {
      img {
        width: 80px;
        // vertical-align: bottom;
      }
      span {
        font-size: 18px;
        vertical-align: middle;
        margin-left: 5px;
        color: #666;
      }
    }
    .van-dropdown-menu__bar {
      box-shadow: none;
    }
    // .van-list {
    //   overflow: hidden;
    // }
    .father {
      .van-cell {
        position: relative;
        float: left;
        background: #fff;
        width: 170px;
        border-radius: 20px;
        overflow: hidden;
        padding: 0;
        margin: 8px;
        margin-top: 10px;
        .houseimg {
          width: 170px;
          height: 154px;
        }
      }
    }
    .bot {
      height: 108px;
      font-size: 18px;
      width: 100%;
      padding: 10px;
      position: relative;
      .sp {
        margin-top: 5px;
      }
      div {
        margin-left: 3px;
        font-size: 18px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        .let {
          font-size: 14px;
          color: #7f7f7f;
        }
      }
      .price {
        font-size: 20px;
        color: red;
        margin-top: 10px;
      }
      .like {
        position: absolute;
        bottom: 18px;
        right: 10px;
        width: 16px;
      }
    }
    .info {
      position: absolute;
      color: #fff;
      top: 130px;
      left: 10px;
    }
    .father {
      min-height: 100px;
      .vant-list {
        height: 100%;
      }
    }
  }
  .back {
    background: #fff;
    position: fixed;
    bottom: 100px;
    right: 10px;
    // border: 1px solid black;
    border-radius: 50%;
  }
  .van-icon-back-top:before {
    font-size: 30px;
  }
}
</style>
